﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WpUserControls
{
    public static class Extensions
    {
        public static void SetHint(this Control textBox, TextBlock hintBox, string hint)
        {
            hintBox.Text = hint;
            hintBox.Foreground = new SolidColorBrush(Colors.Gray);
            hintBox.Tag = textBox;
            textBox.Tag = hintBox;
            hintBox.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(hintBox_Tap);
            textBox.GotFocus += new RoutedEventHandler(textBox_GotFocus);
            textBox.LostFocus += new RoutedEventHandler(textBox_LostFocus);
        }

        static void textBox_GotFocus(object sender, RoutedEventArgs e)
        {
            var textBox = (sender as Control);
            (textBox.Tag as TextBlock).Visibility = Visibility.Collapsed;
        }

        static void hintBox_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var hintBox = (sender as TextBlock);
            hintBox.Visibility = Visibility.Collapsed;
            (hintBox.Tag as Control).Focus();
        }

        static void textBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (sender is TextBox)
            {
                var textBox = (sender as TextBox);
                (textBox.Tag as TextBlock).Visibility = textBox.Text.Length > 0 ? Visibility.Collapsed : Visibility.Visible;
            }
            else if (sender is PasswordBox)
            {
                var passwordBox = (sender as PasswordBox);
                (passwordBox.Tag as TextBlock).Visibility = passwordBox.Password.Length > 0 ? Visibility.Collapsed : Visibility.Visible;
            }
        }

        public static string Truncate(this string str, int start, int length)
        {
            if (str.Length > length + start) return str.Substring(start, length);
            return str.Substring(start);
        }
    }
}
